const { billService } = require('../../services/index');
const app = getApp();

Page({
  data: {
    activeTab: 0,
    billList: [],
    summary: {
      expense: 0,
      income: 0
    },
    isLoading: false,
    userInfo: null
  },

  onLoad() {
    // 检查登录和情侣状态
    if (!app.routeInterceptor()) return;
    
    this.setData({
      userInfo: app.globalData.userInfo
    });
    
    // 加载账单数据
    this.loadBillData();
  },

  onShow() {
    // 每次显示页面时检查数据更新
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      });
    }
  },

  onTabChange(e) {
    this.setData({
      activeTab: e.detail.index
    });
    this.loadBillData();
  },

  async loadBillData() {
    if (!app.globalData.coupleInfo) return;
    
    this.setData({ isLoading: true });
    
    try {
      // 获取账单列表
      const billList = await billService.getCoupleBills(
        app.globalData.coupleInfo.id,
        { type: this.data.activeTab }
      );
      
      // 获取账单统计
      const summary = await billService.getBillSummary(
        app.globalData.coupleInfo.id,
        { month: new Date().getMonth() + 1 }
      );
      
      this.setData({
        billList,
        summary: summary || { expense: 0, income: 0 }
      });
      
    } catch (error) {
      console.error('加载账单失败:', error);
    } finally {
      this.setData({ isLoading: false });
    }
  },

  navToAddBill() {
    wx.navigateTo({
      url: '/pages/bill/add'
    });
  }
});